import traceback
import importlib

from lib import log
from lib.console import cmessage

class CommandManager(object):
	"""
	Keeps track of dynamically handled commands.
	"""
	def __init__(self, world):
		self._world = world
		self._loadedCommands = {}
	
	@property
	def world(self): return self._world
	
	@classmethod
	def tokenize(klass, fullCommand):
		# TODO: make this robust. it can't handle strings... and probably other things
		return fullCommand.split()
		
	def executeCommand(self, player, verb, fullCommand):
		command_handler = self.getOrLoadCommandHandlerForVerb(verb)
		if command_handler is None:
			log.warn('verb {0} does not have a handler'.format(verb))
			cmessage(player, 'Say what?')
			return False
		return command_handler.processVerbFromPlayer(verb, player, fullCommand)
		
	def getOrLoadCommandHandlerForVerb(self, verb, reload = False):
		"""
		Loads the dynamic (custom module) command for the verb.
		Returns the command handler if it loaded; otherwise, None.
		"""
		if verb == "commands": return None # TODO: fix this
		
		# 1. see if the command is already loaded
		if verb in self._loadedCommands:
			if not reload:
				# reload is False, so we just return it
				return self._loadedCommands[verb]
			else:
				# reload = True, so we remove it from the cache
				del self._loadedCommands[verb]
		
		# 2. try to load the command
		try:
			command_module = importlib.import_module(self.world.commandsPackage + "." + verb)
			command_handler_class = getattr(command_module, 'CommandHandler')
			command_handler_object = command_handler_class(self, self._world)
			self._loadedCommands[verb] = command_handler_object
			return command_handler_object
		
		except Exception as e:
			log.error(traceback.format_exc())
			return None
		
		
		
		